/**
 * 1.Promise就是一个类,在执行这个类的时候,需要传递一个执行器进去,执行器会立即执行
 * 2.Promise中有三种状态 分别为 成功 fulfilled 失败 rejected 等待pending
 *   pendding --> fulfilled
 *   pendding --> rejected
 *   一旦状态确定就不可更改
 * 3. resolve和reject函数是用来更改状态的
 *    resolve: 把状态变成成功
 *    reject:  把状态变成失败
 * 4. then 方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数, 如果状态是失败,调用失败的回调函数 then方法是被定义在原型对象中的
 */
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失败
class MyPromise {
  constructor (executor) {
    try { // 捕获执行构造器的错误
      executor(this.resolve, this.reject)
    } catch {
      this.reject(e)
    }
  }
  status = PENDING
  value = undefined
  reason = undefined
  successCallback = []
  failCallback = []
  resolve = (value) => {
    // 如果状态不是等待,阻止程序向下执行
    if (this.status !== PENDING) return
    // 将状态改为成功
    this.status = FULFILLED
    // 保存成功之后的值
    this.value = value
    // 判断成功回调是否存在
    while (this.successCallback.length) this.successCallback.shift()()
  }
  reject = (reason) => {
    // 如果状态不是等待,阻止程序向下执行
    if (this.status !== PENDING) return
    // 将状态改为失败
    this.status = REJECTED
    // 保存失败的原因
    this.reason = reason
    // 判断失败回调是否存在
    while (this.failCallback.length) this.failCallback.shift()()
  }
  then = (successCallback, failCallback) => {
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : reason => {throw reason}
    let promise2 = new MyPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try { // 捕获 then 回调函数的错误
            let x = successCallback(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
            try { // 捕获 then 回调函数的错误
              let x = failCallback(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
      } else {
        this.successCallback.push(() => {
            setTimeout(() => {
                try { // 捕获 then 回调函数的错误
                  let x = successCallback(this.value)
                  /**
                  * 判断 x 值是普通值还是promise对象
                  * 如果是普通值,直接调用resolve
                  * 如果是promise对象 查看promise对象返回的结果
                  * 再根据promise对象返回的结果, 决定调用 resolve 还是调用 reject
                */
                  // resolve(x)
                  resolvePromise(promise2, x, resolve, reject)
                } catch (e) {
                  reject(e)
                }
              }, 0)
        })
        this.failCallback.push(() => {
            setTimeout(() => {
                try { // 捕获 then 回调函数的错误
                  let x = failCallback(this.reason)
                  /**
                  * 判断 x 值是普通值还是promise对象
                  * 如果是普通值,直接调用resolve
                  * 如果是promise对象 查看promise对象返回的结果
                  * 再根据promise对象返回的结果, 决定调用 resolve 还是调用 reject
                */
                  // resolve(x)
                  resolvePromise(promise2, x, resolve, reject)
                } catch (e) {
                  reject(e)
                }
              }, 0)
        })
      }
    })
    // then方法返回promise,为了实现链式调用
    return promise2
  }
  catch (failCallback) {
    return this.then(undefined, failCallback)
  }
  finally (callback) {
    return this.then(
      value => MyPromise.resolve(callback()).then(() => value),
      reason => MyPromise.resolve(callback()).then(() => {throw reason})
    )
  }
  done (onFulfilled, onRejected) {
    this.then(onFulfilled, onRejected)
        .catch(reason => {
          setTimeout(() => {throw reason}, 0)
        })
  }
  static all (array) {
    let result = []
    let index = 0
    return new Promise((resolve, reject) => {
      function addData (key, value) {
        result[key] = value
        index++
        if (index === array.length) {
          resolve(result)
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i]
        if (current instanceof MyPromise) {
          current.then(value => addData(i, value), (reason) => reject(reason))
        } else {
          addData(i, array[i])
        }
      }
    })
  }
  static resolve (value) {
    // 如果value是MyPromise的实例,直接返回value
    if (value instanceof MyPromise) return value
    // 如果不是返回promise
    return new MyPromise(resolve => resolve(value))
  }
}
function resolvePromise (promise2, x, resolve, reject) {
  // 判断类型错误
  if (promise2 === x) {
    return reject (new Error('Chaning cycle detected'))
  }
  if (x instanceof MyPromise) { // 判断 x 是不是MyPromise的实例
    // promise对象
    // 如果是promise对象 查看promise对象返回的结果
    // 再根据promise对象返回的结果, 决定调用 resolve 还是调用 reject
    x.then(resolve, reject)
  } else {
    // 普通值
    // 如果是普通值,直接调用resolve
    resolve(x)
  }
}
module.exports = MyPromise